layui.define(['table', 'form', 'admin', 'ax', 'upload'], function (exports) {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var form = layui.form;
    var upload = layui.upload;
    var prepareData = "";//暂存的表格数据
    /**
     * 装修预算表管理
     */
    var ZxYusuan = {
        tableId: "zxYusuanTable"
    };

    /**
     * 初始化表格的列
     */
    ZxYusuan.initColumn = function () {
        return [[
            { field: 'btyZxYusuanId', hide: true, title: '主键' },
            // {field: 'btyBrandIdView', sort: true, title: '装修门店'},
            { field: 'xuhao', sort: true, title: '序号', edit: 'text', width: 70, align: "center", fixed: true },
            { field: 'xiangmu', sort: true, title: '项目名称', edit: 'text', align: "left", fixed: true },
            { field: 'sjdw', sort: true, title: '时间单位', edit: 'text', align: "center" },
            { field: 'danjia', sort: true, title: '单价', width: 70, edit: 'text', align: "center" },
            { field: 'jine', sort: true, title: '预算金额', totalRow: true, edit: 'text', align: "center" },
            { field: 'bz', sort: true, title: '备注', edit: 'text', align: "center" },
            // {field: 'yusuanLock', sort: true, title: '状态',edit: 'text',},
            // {field: 'status', sort: true, title: '状态'},
            // {field: 'statusView', sort: true, title: '状态显示'},
            // {field: 'delFlag', sort: true, title: '删除标记'},
            // {field: 'createUser', sort: true, title: '创建人'},
            // {field: 'createUserName', sort: true, title: '创建人姓名'},
            // {field: 'createTime', sort: true, title: '创建时间'},
            // {field: 'updateUser', sort: true, title: '更新人'},
            // {field: 'updateUserName', sort: true, title: '更新人姓名'},
            // {field: 'updateTime', sort: true, title: '更新时间'},
            // {field: 'company', sort: true, title: '所属组织'},
            // {field: 'companyView', sort: true, title: '所属组织显示'},
            // {field: 'srcType', sort: true, title: '上级单据'},
            // {field: 'srcValue', sort: true, title: '上级单据值'},
            { align: 'center', templet: '#statusTpl', title: '状态' }
        ]];
    };


    /**
     * 初始化门店
     */
    var languageAjax = new $ax(Feng.ctxPath + "/mdzx/mdzxList");
    var languageResult = languageAjax.start();
    console.info(languageResult);
    $.each(languageResult.data, function (index, val) {
        if (val.btyBrandIdView != undefined) {
            var pinyin = ConvertPinyin(val.btyBrandIdView);

            if (val.yusuanLock == 1) {
                //导出需要选择的门店
                // $("#btyZxMdzxIdDaoChu").append("<option value='" + val.btyZxMdzxId + "'>" +"🔒"+ val.btyBrandIdView+"-"+pinyin + "</option>");
                //添加要选择的门店
                // $("#btyZxMdzxId").append("<option value='" + val.btyZxMdzxId + "'>" + "🔒"+val.btyBrandIdView +"-"+pinyin+ "</option>");
            } else {
                //导出需要选择的门店
                // $("#btyZxMdzxIdDaoChu").append("<option value='" + val.btyZxMdzxId + "'>" + val.btyBrandIdView+"-"+pinyin + "</option>");
                //添加要选择的门店
                // $("#btyZxMdzxId").append("<option value='" + val.btyZxMdzxId + "'>" + val.btyBrandIdView +"-"+pinyin+ "</option>");
            }

        }
    });
    form.render('select');

    /**
     * 点击查询按钮
     */
    ZxYusuan.search = function () {
        var queryData = {};
        queryData['btyZxMdzxId'] = $("#btyZxMdzxIdDaoChu").val();
        queryData['yusuanLock'] = $("#yuSuanLock").val();
        table.reload(ZxYusuan.tableId, { where: queryData });
    };
    /**
     * 点击查询按钮
     */
    ZxYusuan.searchById = function (btyZxMdzxId) {
        var queryData = {};
        queryData['btyZxMdzxId'] = btyZxMdzxId;
        table.reload(ZxYusuan.tableId, { where: queryData });
    };

    /**
     * 弹出添加对话框
     */
    ZxYusuan.openAddDlg = function () {
        window.location.href = Feng.ctxPath + '/zxYusuan/add';
    };

    /**
     * 导出excel按钮
     */
    // ZxYusuan.exportExcel = function () {
    //     var checkRows = table.checkStatus(ZxYusuan.tableId);
    //     if (checkRows.data.length === 0) {
    //         Feng.error("请选择要导出的数据");
    //     } else {
    //         table.exportFile(tableResult.config.id, checkRows.data, 'xls');
    //     }
    // };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    ZxYusuan.openEditDlg = function (data) {
        window.location.href = Feng.ctxPath + '/zxYusuan/edit?btyZxYusuanId=' + data.btyZxYusuanId + "&btyZxMdzxId=" + $("#btyZxMdzxIdDaoChu").val();
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    ZxYusuan.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/zxYusuan/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(ZxYusuan.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("btyZxYusuanId", data.btyZxYusuanId);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + ZxYusuan.tableId,
        url: Feng.ctxPath + '/zxYusuan/list',
        page: false,
        cellMinWidth: 100,
        limit: 100,
        height: "full-158",
        totalRow: true,
        cols: ZxYusuan.initColumn(),
        where: {
            'btyZxMdzxId': "-1"
        },
        done: function (data) {
            data.data.map(item => {
                item.jine = item.jine ? item.jine : ''
            })
            // prepareData = JSON.parse(JSON.stringify(data.data))
            prepareData = data.data

        }
    });

    //带入查询条件
    if (Feng.getUrlParam("btyZxMdzxId") != null) {
        // $("#btyZxMdzxIdDaoChu").val(Feng.getUrlParam("btyZxMdzxId"));
        form.render('select');
        ZxYusuan.search();
    }

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        ZxYusuan.search();
    });

    //预算锁定
    $('#lockYusuan').click(function () {
        var btyZxMdzxIdDaoChu = $("#btyZxMdzxIdDaoChu").val();
        var yuSuanLock = $("#yuSuanLock").val();
        var yusuanLockPass = $("#yusuanLockPass").val();

        if (btyZxMdzxIdDaoChu == "") {
            Feng.error("请选择一个门店");
            return false;
        }
        if (yuSuanLock == "") {
            Feng.error("请选择状态");
            return false;
        }
        if (yusuanLockPass == "") {
            if (yuSuanLock == 1) {
                Feng.error("请输入锁定密码");
            } else if (yuSuanLock == 0) {
                Feng.error("请输入解锁密码");
            }
            return false;
        }

        var reg = new RegExp(/^\d{6}$/);
        if (!reg.test(yusuanLockPass)) {
            Feng.error("请输入6位数字密码");
            return false;
        }


        var ajax = new $ax(Feng.ctxPath + "/mdzx/yuSuanLockEdit", function (data) {
            if (data.code == 200) {
                if (yuSuanLock == 1) {
                    Feng.success("锁定成功");
                } else if (yuSuanLock == 0) {
                    Feng.success("解锁成功");
                }
                var queryData = {};
                queryData['btyZxMdzxId'] = $("#btyZxMdzxIdDaoChu").val();
                queryData['yusuanLock'] = $("#yuSuanLock").val();
                table.reload(ZxYusuan.tableId, { where: queryData });
                ZxYusuan.reloadSelect($("#btyZxMdzxIdDaoChu").val(), $("#btyZxMdzxId").val());
                $("#yusuanLockPass").val("");
            } else {
                Feng.error(data.message);
            }
        }, function (data) {
            Feng.error("失败!" + data.responseJSON.message + "!");
        });
        ajax.set("yusuanLockPass", yusuanLockPass);
        ajax.set("yusuanLock", yuSuanLock);
        ajax.set("btyZxMdzxId", btyZxMdzxIdDaoChu);
        ajax.start();
    });


    ZxYusuan.reloadSelect = function (mdid, mdid2) {
        $("#btyZxMdzxIdDaoChu").html("");
        $("#btyZxMdzxId").html("");
        $("#btyZxMdzxIdDaoChu").append("<option value=''>" + "请选择装修门店" + "</option>");
        $("#btyZxMdzxId").append("<option value=''>" + "请选择装修门店" + "</option>");
        var languageAjax = new $ax(Feng.ctxPath + "/mdzx/mdzxList");
        var languageResult = languageAjax.start();
        console.info(languageResult);

        $.each(languageResult.data, function (index, val) {
            if (val.btyBrandIdView != undefined) {
                var pinyin = ConvertPinyin(val.btyBrandIdView);
                if (val.yusuanLock == 1) {
                    //导出需要选择的门店
                    $("#btyZxMdzxIdDaoChu").append("<option value='" + val.btyZxMdzxId + "'>" + "🔒" + val.btyBrandIdView + "-" + pinyin + "</option>");
                    //添加要选择的门店
                    $("#btyZxMdzxId").append("<option value='" + val.btyZxMdzxId + "'>" + "🔒" + val.btyBrandIdView + "-" + pinyin + "</option>");
                } else {
                    //导出需要选择的门店
                    $("#btyZxMdzxIdDaoChu").append("<option value='" + val.btyZxMdzxId + "'>" + val.btyBrandIdView + "-" + pinyin + "</option>");
                    //添加要选择的门店
                    $("#btyZxMdzxId").append("<option value='" + val.btyZxMdzxId + "'>" + val.btyBrandIdView + "-" + pinyin + "</option>");
                }

            }
        });
        $('#btyZxMdzxIdDaoChu').val(mdid);
        $('#btyZxMdzxId').val(mdid2);
        form.render('select');
    };

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        ZxYusuan.openAddDlg();
    });
    // 刷新页面
    $('#refresh').click(function () {
        window.location.href = Feng.ctxPath + '/zxYusuan';
    });

    // 工具条点击事件
    table.on('tool(' + ZxYusuan.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        // if (layEvent === 'edit') {
        //     ZxYusuan.openEditDlg(data);
        // } else if (layEvent === 'delete') {
        //     ZxYusuan.onDeleteItem(data);
        // }
    });



    // // 导出excel
    // $('#btnExp').click(function () {
    //     ZxYusuan.exportExcel();
    // });
    // /**
    //  * 导出excel按钮
    //  */
    // ZxYusuan.exportExcel = function () {
    //     //选择了门店才可以导出
    //     var btyZxMdzxIdDaoChu = $("#btyZxMdzxIdDaoChu").val();
    //     if (btyZxMdzxIdDaoChu == "" || btyZxMdzxIdDaoChu == undefined || btyZxMdzxIdDaoChu == null) {
    //         Feng.error("请先选择装修门店");
    //     } else {
    //         //获取导出Excel的数据
    //         var url = Feng.ctxPath + "/zxYusuan/listExport?btyZxMdzxId=" + btyZxMdzxIdDaoChu;
    //         location.href = url;
    //     }
    // };


    //初始化预算数据
    $('#initYuSuan').click(function () {
        //选择了门店才可以导出
        var btyZxMdzxIdDaoChu = $("#btyZxMdzxIdDaoChu").val();
        if (btyZxMdzxIdDaoChu == "" || btyZxMdzxIdDaoChu == undefined || btyZxMdzxIdDaoChu == null) {
            Feng.error("请先选择装修门店");
            return false;
        }
        var btyBrandIdView = $("#btyBrandIdView").val();
        //Feng.confirm("门店："+btyBrandIdView+"，如果已存在预算数据，将会覆盖，是否继续?", operation);

        layer.confirm("如果已存在预算数据，将会覆盖，是否继续?",
            { icon: 0, btn: ['继续', '取消'], title: btyBrandIdView },
            function (index) {
                var ajax = new $ax(Feng.ctxPath + "/zxYusuan/initYusuanData", function (data) {
                    if (data.code == 200) {
                        layer.close(index);
                        Feng.success("初始化成功!");
                        layui.shuxinMd();
                        table.reload(ZxYusuan.tableId);
                    } else {
                        layer.close(index);
                        Feng.error(data.message);
                    }

                }, function (data) {
                    Feng.error("初始化失败!" + data.responseJSON.message + "!");
                });
                //选择了门店才可以导出
                var btyZxMdzxIdDaoChu = $("#btyZxMdzxIdDaoChu").val();
                ajax.set("btyZxMdzxId", btyZxMdzxIdDaoChu);
                ajax.start();
            },
            function (index) { layer.close(index); }
        )

    });



    function validate_bt() {
        var btyZxMdzxId = $("#btyZxMdzxId").val();

        if (btyZxMdzxId == "") {
            Feng.error("请先选择装修门店");
            return false;
        }
        var yujiTouzi = $("#yujiTouzi").val();

        if (yujiTouzi == "") {
            Feng.error("请输入预计投资！");
            return false;
        }
        return true;
    }

    //表单提交事件
    form.on('submit(btnSubmit)', function (data) {
        if (validate_bt()) {
            var ajax = new $ax(Feng.ctxPath + "/mdzx/editYujiTouzi", function (data) {
                if (data.code == 200) {
                    $("#yujiTouzi").val("");
                    Feng.success("预算总计投资金额修改成功！");
                    layui.shuxinMd();
                } else {
                    Feng.error(data.message);
                }
            }, function (data) {
                Feng.error("预算总计投资金额修改失败！" + data.responseJSON.message);
            });
            ajax.set(data.field);
            ajax.start();
            return false;
        } else {
            return false;
        }
    });

    // form.on('select(btyZxMdzxId)',function (data) {
    //     var btyZxMdzxId = $("#btyZxMdzxId").val();
    //     $.ajax({
    //         type: "PUT",
    //         url: "/zxYusuan/getMaxXuhao",
    //         datatype: "json",
    //         data: {
    //             btyZxMdzxId:btyZxMdzxId
    //         },
    //         success: function (data) {
    //             $("#xuhao").val(data.data);
    //         }, error: function () {
    //             Feng.error("修改失败！");
    //         }, complete: function (XHR, TS) { }
    //     });
    // });

    __log = function (msg) {
        setTimeout(() => {
            throw new Error(msg);
        }, 0);
    }

    //监听单元格编辑

    table.on('edit(zxYusuanTable)', function (obj) {
        var value = obj.value, //得到修改后的值
            data = obj.data, //得到所在行所有键值
            field = obj.field; //得到字段

        let budgetPrice = data.jine ? data.jine : '';//重新计算的预算金额
        let total = 0

        if (field == "danjia") {
            // 修改单价时
            if (value && data.mianji) {
                let price = parseFloat(value)
                budgetPrice = (price * data.mianji).toFixed(2);//计算的预算金额
            } else {
                budgetPrice = prepareData[data.xuhao - 1].jine;//计算的预算金额
            }
            const tableData = table.cache.zxYusuanTable
            tableData.map(item => {
                if (item.btyZxYusuanId == data.btyZxYusuanId) {
                    if (!budgetPrice) {
                        return
                    }
                    total = total + parseFloat(budgetPrice)
                    return
                }
                if (item.jine) {
                    total = total + parseFloat(item.jine)
                }
            })
            total = total.toFixed(4)
        }
        if (field == "jine") {
            // 修改预算金额时重新计算合计金额
            const tableData = table.cache.zxYusuanTable
            tableData.map(item => {
                if (item.btyZxYusuanId == data.btyZxYusuanId) {
                    if (!obj.value) {
                        return
                    }
                    total = total + parseFloat(obj.value)
                    return
                }
                if (item.jine) {
                    total = total + parseFloat(item.jine)
                }
            })
            total = total.toFixed(4)
        }
        var selector = obj.tr.selector + ' td[data-field="' + obj.field + '"] div';
        var oldtext = $(selector).text();

        // __log(JSON.stringify(obj))

        //锁定时不可修改
        if (data.yusuanLock == 1) {
            Feng.error("修改失败，该店数据已经锁定，如需编辑请先解锁");
            $(obj.tr.selector + ' td[data-field="' + obj.field + '"] input').val(oldtext);
            // table.reload(ZxYusuan.tableId);
            return false;
        }

        //金额字段校验
        if (field == "jine" && isNaN(value)) {
            Feng.error("修改失败，金额必须填写数字");
            $(obj.tr.selector + ' td[data-field="' + obj.field + '"] input').val(oldtext);
            return false;
        }
        $.ajax({
            type: "PUT",
            url: "/zxYusuan/editItem",
            datatype: "json",
            data: data,
            success: function (data) {
                layui.shuxinMd();
                if (field == "jine" || field == "danjia") {
                    $("#zxYusuanTable").next().find('.layui-table-total').find('td[data-field="jine"] div').text(total)
                    if (field == "danjia") {
                        obj.update({
                            ...data, jine: budgetPrice
                        })
                    }
                }
                // $(obj.tr.selector + ' td[data-field="' + obj.field + '"] input').val(value)
                // Feng.success("修改成功！");
                // setTimeout(() => {
                //     obj.update(obj)
                // }, 100)
                // table.reload(ZxYusuan.tableId);
            }, error: function () {
                Feng.error("修改失败！");
            }, complete: function (XHR, TS) { }
        });
    });

    //门店装修-预算导入
    var loadIndex;
    upload.render({
        elem: '#btnExcel'
        , url: '/zxYusuan/import'
        , accept: "file"
        , async: false
        , exts: 'xls|xlsx|xlsm|xlt|xltx|xltm'
        , before: function () {
            //this.data = {'dataTime': $('#dataTime').val()};//关键代码
            loadIndex = layer.load(2, { shade: [0.15, '#ccc'] });
        }
        , done: function (data) {
            if (data.code == 200) {
                Feng.success("预算信息导入成功");
                // window.location.reload();
                layer.close(loadIndex);
                table.reload(ZxYusuan.tableId);
            } else {
                Feng.error(data.message);
                layer.close(loadIndex);
            }

        }
    });


    // 添加按钮点击事件
    $('#copyBtn').click(function () {
        ZxYusuan.openCopyYusuan();
    });


    /**
     * 弹出添加对话框
     */
    ZxYusuan.openCopyYusuan = function () {
        // window.location.href = Feng.ctxPath + '/zxYusuan/copyIndex';
        parent.layer.open({
            type: 2,
            title: '新增门店',
            area: ['80%', '80%'],
            content: Feng.ctxPath + '/zxYusuan/copyIndex',
            end: function () {
                layui.shuxinMd();
            },
            cancel: function (index) {
                layui.shuxinMd();
            }
        });
    };

    exports('shuxinYusuan', function (btyZxMdzxId, btyBrandIdView) {//函数参数
        ZxYusuan.searchById(btyZxMdzxId);
        $("#btyZxMdzxIdDaoChu").val(btyZxMdzxId);
        $("#btyBrandIdView").val(btyBrandIdView);
        $("#btyZxMdzxId").val(btyZxMdzxId);
    });
});
